/**
 * 
 * @file authn.c
 * @brief Authentication module
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "nweb.h"
#include "authn.h"
#include "http_status.h"

#include "digest_auth.h"
#include "basic_authn.h"

auth_config* get_auth_config(request_rec *r) {
	FILE *ifp = fopen(".htaccess", "r");
	
	auth_config *config = malloc(sizeof(*config));
	char *auth_type = malloc(256);
	char *auth_user_file = malloc(256);
	
	if (ifp) {
		fscanf(ifp, "AuthType %s[^\n]", auth_type);
		fgetc(ifp); //points  at \n and fgetc points to the next line
		fscanf(ifp, "AuthUserFile %s[^\n]", auth_user_file);
	}
	
	config->auth_type = auth_type;
	config->auth_user_file = auth_user_file;
	
	return config;
}

authn_provider lookup_provider(const char *provider_name) {
    if (strcmp(provider_name, "Digest") == 0) {
	return authenticate_digest_user;
    }
    else if (strcmp(provider_name, "Basic") == 0) {
    	return authenticate_basic_user;
    }
    else {
	// Always return OK
	return authenticate_default;
    }
}

void register_authn_provider(request_rec *r) {
    auth_config *config = get_auth_config(r);
    authn_provider provider = lookup_provider(config->auth_type);
    run_check_user_id = provider;
}

int authenticate_default(request_rec *r) {
    return OK;
}
